package com.easy.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.SysPermission;
import com.easy.common.bean.SysRole;
import com.easy.common.enumbean.RoleStatus;
import com.easy.common.service.IRoleService;
import com.easy.user.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService extends ServiceImpl<RoleMapper, SysRole> implements IRoleService {
@Autowired
    RoleMapper roleMapper;
    @Override
    public SysRole insert(SysRole role) {
        roleMapper.insert(role);
        SysRole result=roleMapper.selectById(role.getId());
        return result;
    }

    @Override
    public SysRole update(SysRole role) {
        roleMapper.updateById(role);
        SysRole result=roleMapper.selectById(role.getId());
        return result;
    }

    @Override
    public int delete(Integer id) {
       return roleMapper.deleteById(id);
    }

    @Override
    public SysRole getByID(Integer id) {
        SysRole role=roleMapper.selectById(id);
        role.setPermissions(getRolePermissions(role));
        return role;
    }

    @Override
    public IPage<SysRole> getListByPage(IPage page, SysRole role) {
        QueryWrapper wrapper=new QueryWrapper<>(role);
        IPage <SysRole> result=roleMapper.selectPage(page,wrapper);
        for(SysRole item:result.getRecords()){
            item.setPermissions(getRolePermissions(item));
        }
        return result;
    }

    @Override
    public List<SysRole> getList(SysRole role) {
        QueryWrapper wrapper=new QueryWrapper(role);
        return roleMapper.selectList(wrapper);
    }

    @Override
    public int setStatus(Integer id) {
        SysRole role=roleMapper.selectById(id);
        if(role.getStatus()== RoleStatus.DISABLE){
            role.setStatus(RoleStatus.NORMAL);
        }else{
            role.setStatus(RoleStatus.DISABLE);
        }
       return roleMapper.updateById(role);
    }

    @Override
    public SysRole assignPermission(SysRole role) {
        roleMapper.clearRolePermission(role.getId());
        for(SysPermission per:role.getPermissions()){
            roleMapper.assignPermission(role.getId(),per.getId());
        }
        SysRole result=roleMapper.selectById(role.getId());
        result.setPermissions(getRolePermissions(result));
        return result;
    }

    @Override
    public List<SysPermission> getRolePermissions(SysRole role) {
        List<SysPermission> permissions=this.getBaseMapper().getRolePermissions(role.getId());
        return permissions;
    }
}
